import React, { useEffect, useRef, useState } from 'react';
import Vditor from 'vditor';
import "vditor/dist/index.css";
import styles from './vditor.less';;
import request from '@/utils/request';
import { upload } from '@/services/vditor';
import iconImg from '@/assets/knowledgeFile/2.svg';
var vditor = null, vditorNew = 0;

function MarkdownEditor(props) {
    const editorRef = useRef(null);
    const [title, setTitle] = useState(null);
    const [vditorCurrent,setVditorCurrent] = useState({})
    useEffect(() => {
      console.log(editorRef);
        var vditor = new Vditor(editorRef.current, {
            value: props.value,
            cache: false,
            input: (value) => props.onChange(value, 'content'),
            // cache: { id: 'vditor' },
            height: props.height,
            cdn: staticPath + '/vditor',
            counter: { enable: true },
            toolbar: [
                'emoji', 'headings', 'bold', 'italic', 'strike', 'link', '|',
                'list', 'ordered-list', 'check', 'outdent', 'indent', '|',
                'quote', 'line', 'code', 'inline-code', 'insert-before', 'insert-after', '|',
                'upload', /** 'record', */ 'table', '|', 'undo', 'redo', '|',
                /** 'fullscreen', 'edit-mode', */
                {
                    name: "edit-mode",
                    tip: "切换编辑模式",
                    icon: `<img style="height: 16px" src="${iconImg}" />`,
                },
                // 'both', 'preview', 'outline', 'code-theme', 'content-theme', 'export', 'devtools', 'info', 'help', 'br'
            ],
            placeholder: "请输入正文",
            preview: {
                show: false,
                actions: [],
            },
            after: () => {
                vditorNew = 1;
                setTitleAsync(1);
                // setTimeout(setTitleAsync, 10);
                // instance.setValue(props.content)
            },
            upload: {
                // accept: 'image/jpeg,image/png,image/gif,image/jpg,image/bmp', // 图片格式
                // max: 2 * 1024 * 1024,  // 控制大小
                multiple: true, // 是否允许批量上传
                fieldName: 'file', // 上传字段名称
                url: '/cloud/file/upload',
                success: function (textarea, msg) {//textarea  
                    //将返回的信息传为json对象 
                    let msgData = JSON.parse(msg)
                    if (msgData?.state === "SUCCESS") {//请求成功  
                      vditorCurrent[props.id].tip('上传成功', 1500);
                        let content;
                        //获取文件后缀，判断类型  
                        let temp = msgData.original.substring(msgData.original.lastIndexOf('.') + 1)
                        if (temp == "png" || temp == "jpg") {
                            content = "![" + msgData.original + "](" + msgData.url + ")"
                        } else {
                            content = "[" + msgData.original + "](" + msgData.url + ")"
                        };
                        //插入上传文件后的markdown代码  
                        vditorCurrent[props.id].insertValue(content)
                    }
                }
                // 文件名安全处理
                // filename(name) {
                //     return name
                //         .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '')
                //         .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, '')
                //         .replace('/\\s/g', '');
                // },
                // 遍历文件上传并展示
                // async handler(files) {
                //     let res;
                //     for (const file of files) {
                //         const name = file.name;
                //         const formData = new FormData();
                //         formData.append('file', file);
                //         res = await upload(formData);
                //         console.log(res);
                //         editorRef.current?.insertValue(`![${name}](${res.uplaodRes})`); // 文本编辑器中插入图片
                //     }
                //     if (res.uplaodRes) {
                //         return '上传成功';
                //     }
                //     return '上传失败';
                // },
            },
        });
         vditorCurrent[props.id] = vditor
        setVditorCurrent(vditorCurrent)
        if(props.setVditorRef){
          props.setVditorRef(vditor)
        }
        // 加载文本标题
        // setTimeout(setTitleAsync, 1000);
        return () => {
			vditorNew = 0;
            setTitle(null);
		};
    }, [])

    useEffect(() => {
        // 3秒后更改编辑器内容
        // setTimeout(setEditorContentAsync, 3000)
        if (props.title == '' || props.value == '') { } else {
            // setTimeout(setEditorContentAsync, 3)
            if (vditorNew == 1) {
                setEditorContentAsync()
                // setTimeout(setEditorContentAsync, 500)
            }
        }
    }, [props.title, vditorNew, title])

    // useEffect(() => {
    //     // 3秒后更改编辑器内容
    //     // setTimeout(setEditorContentAsync, 3000)
    //     if (props.title == '' || props.value == '') { } else {
    //         if (vditorNew === 1) {
    //             setTimeout(setEditorContentAsync, 200)
    //         }
    //     }
    // }, [vditorNew])
    

    const setTitleAsync = (type) => {
        setTitle(type);
        let bfContainer = document.getElementById('markdown-editor');
        let bfContent = document.getElementsByClassName('vditor-content')[0];
        var node = document.createElement("div");
        node.setAttribute("class", "bf-input");
        node.innerHTML = `
        <input
          style="
            height: 48px;
            width: 100%;
            border: 0px;
            font-size: 24px;
            font-weight: bold;
            outline: none;
            box-shadow: none;
            color: #000000cc;
            padding: 0 12px;
            border-bottom: 1px solid #d4d4d4;
          "
          class="bf-headerTitle"
          id="bf-headerTitle"
          value="${props.title}"
          placeholder="请输入标题"
        />`;
        node.children[0].onchange = e => {
            // console.log(e.target.value);
            props.onChange(e.target.value, 'title');
            node.children[0].blur();
        };
        node.children[0].onkeydown = e => {
            if (e.keyCode === 13) {
                // console.log(e.target.value);
                props.onChange(e.target.value, 'title');
                // vditor.focus();
                node.children[0].blur();
            }
        };
        if(!props.noTitle){
          bfContainer.insertBefore(node, bfContent);
        }
    }

    const setEditorContentAsync = () => {
        if (document.getElementById("bf-headerTitle")) {
            document.getElementById("bf-headerTitle").value = props.title;
        }
        if (vditorCurrent[props.id] && vditorCurrent[props.id].setValue && props.title && props.title !== '') {
          vditorCurrent[props.id].setValue(props.value);
        }
    };

    return (
        <div className={styles["markdown-editor"]} id={props.id} ref={editorRef}></div>
    )
}

export default React.forwardRef(MarkdownEditor);
